package com.atguigu.day09;

import com.atguigu.util.Event;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

// 订单超时检测
public class Example3 {
    public static void main(String[] args) throws Exception {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        var stream = env
                .addSource(new SourceFunction<Event>() {
                    @Override
                    public void run(SourceContext<Event> ctx) {
                        ctx.collectWithTimestamp(new Event("order-1", "create-order", 1000L), 1000L);
                        ctx.collectWithTimestamp(new Event("order-2", "create-order", 2000L), 2000L);
                        ctx.collectWithTimestamp(new Event("order-1", "pay-order", 4000L), 4000L);
                    }

                    @Override
                    public void cancel() {

                    }
                });

        var pattern = Pattern
                .<Event>begin("create")
                .where(new SimpleCondition<>() {
                    @Override
                    public boolean filter(Event event) {
                        return event.type.equals("create-order");
                    }
                })
                .next("pay")
                .where(new SimpleCondition<>() {
                    @Override
                    public boolean filter(Event event) {
                        return event.type.equals("pay-order");
                    }
                })
                // 设置两个事件必须在5秒钟之内发生
                .within(Time.seconds(5));

        var result = CEP
                .pattern(stream.keyBy(r -> r.key), pattern)
                .flatSelect(
                        // 侧输出流，用来接收超时信息
                        new OutputTag<>("timeout-info") {
                        },
                        // 用来将超时信息发送给侧输出流的匿名类
                        new PatternFlatTimeoutFunction<Event, String>() {
                            @Override
                            public void timeout(Map<String, List<Event>> map, long timeoutTs, Collector<String> collector) {
                                // map {
                                //    "create": [Event]
                                // }
                                var create = map.get("create").get(0);
                                // 发送到侧输出流
                                collector.collect(create.key + "超时未支付, 在" + timeoutTs + "之前没有支付");
                            }
                        },
                        // 处理已经支付的订单
                        new PatternFlatSelectFunction<Event, String>() {
                            @Override
                            public void flatSelect(Map<String, List<Event>> map, Collector<String> collector) {
                                // map {
                                //   "create": [Event],
                                //   "pay": [Event]
                                // }
                                var create = map.get("create").get(0);
                                var pay = map.get("pay").get(0);
                                collector.collect(create.key + "已经支付，支付时间是：" + pay.ts);
                            }
                        }
                );

        result.print("main");

        result.getSideOutput(new OutputTag<String>("timeout-info"){}).print("side");

        env.execute();
    }
}
